package com.smarthealthring.mm.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.smarthealthring.mm.R;
import com.smarthealthring.mm.base.BaseActivity;
import com.smarthealthring.mm.bean.RegistRes;
import com.smarthealthring.mm.constant.ComConstant;
import com.smarthealthring.mm.contract.UserRegistContract;
import com.smarthealthring.mm.presenter.UserRegistPresenter;
import com.smarthealthring.mm.utils.GlideApp;
import com.smarthealthring.mm.utils.RandomUtil;
import com.smarthealthring.mm.utils.RegexUtils;
import com.smarthealthring.mm.utils.SPUtils;
import com.smarthealthring.mm.utils.ToastUtil;
import com.smarthealthring.mm.widgets.CleanEditText;
import com.jakewharton.rxbinding2.view.RxView;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.reactivestreams.Subscription;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

import static com.smarthealthring.mm.utils.SPUtils.TOKEN;
import static com.smarthealthring.mm.utils.SPUtils.USERID;
import static com.smarthealthring.mm.utils.SPUtils.USERNAME;

/**
 * 用户注册
 */
public class UserRegistActivity extends BaseActivity<UserRegistPresenter> implements UserRegistContract.View {
    @BindView(R.id.tv_xieyi)
    TextView mTvXieyi;
    TextView mTvVerify;
    @BindView(R.id.tv_phoneno)
    CleanEditText mEtPhoneNo;
    @BindView(R.id.et_password)
    EditText mEtPassword;
    @BindView(R.id.tv_regist)
    TextView mTvRegist;
    @BindView(R.id.et_verifycode)
    CleanEditText mEtVerifyCode;
    @BindView(R.id.iv_pw_visible)
    ImageView mImgPwVisble;

    private int isShowPwd = 0;

    @Override
    protected void initComToolBar() {

    }

    @Override
    protected int getLayout() {
        return R.layout.act_user_regist;
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initEventAndData(@Nullable Bundle savedInstanceState) {
        //        mTvXieyi.setText("我已阅读并同意");
        //        String str = "《用户协议》";
        //        SpannableString spanStr = new SpannableString(str);
        //        spanStr.setSpan(new ClickableSpan() {
        //            @Override
        //            public void onClick(View widget) {
        //                ToastUtil.shortShow("协议!!");
        //            }
        //        }, 0, str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //        mTvXieyi.append(spanStr);
        //        spanStr.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.colorPrimary)),
        //                7,mTvXieyi.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //        spanStr.setSpan(new MyUnderlineSpan(),
        //                7,mTvXieyi.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //        mTvXieyi.setHighlightColor(Color.TRANSPARENT);
        //        mTvXieyi.setMovementMethod(LinkMovementMethod.getInstance());
        //获取短信验证码
        mTvVerify = findViewById(R.id.tv_get_verifycode);
        RxView.clicks(mTvVerify)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        String phoneNo = mEtPhoneNo.getText().toString().trim();

                        if (TextUtils.isEmpty(phoneNo)) {
                            ToastUtil.shortShow("请输入手机号码");
                            return;
                        }
                        if (!RegexUtils.isMobileExact(phoneNo)) {
                            ToastUtil.shortShow("手机号码格式不正确!");
                            return;
                        }
                        mPresenter.getVerifyCode(new HashMap<String, String>() {{
                            put("trans_id", "1001");
                            put("nonce_str", RandomUtil.getRandomString(32));
                            put("mobile", phoneNo);
                            put("vercodetype", ComConstant.MSG_REGIST);
                        }});
                        count(); //倒计时
                    }
                });

        //设置密码
        RxView.clicks(mTvRegist)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        String phoneNo = mEtPhoneNo.getText().toString().trim();
                        String password = mEtPassword.getText().toString().trim();
                        String verifyCode = mEtVerifyCode.getText().toString().trim();
                        if (TextUtils.isEmpty(phoneNo)) {
                            ToastUtil.shortShow("请输入手机号码");
                            return;
                        }
                        if (TextUtils.isEmpty(verifyCode)) {
                            ToastUtil.shortShow("请输入验证码");
                            return;
                        }
                        if (TextUtils.isEmpty(password)) {
                            ToastUtil.shortShow("请输入密码");
                            return;
                        }
                        if (password.length() < 6) {
                            ToastUtil.shortShow("密码至少为6位");
                            return;
                        }

                        mPresenter.regist(new HashMap<String, String>() {{
                            put("trans_id", "2001");
                            put("nonce_str", RandomUtil.getRandomString(32));
                            put("username", phoneNo);
                            put("password", password);
                            put("captchamsg", verifyCode);
                        }});
                    }
                });

        // 默认看不见密码
        mEtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        GlideApp.with(mContext).load(R.drawable.pw_invisible).into(mImgPwVisble);

        mImgPwVisble.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowPwd == 0) {
                    isShowPwd = 1;
                    GlideApp.with(mContext).load(R.drawable.pw_visible).into(mImgPwVisble);
//                    mImgPwVisble.setBackgroundResource(R.drawable.pw_visible);
                } else {
                    isShowPwd = 0;
                    GlideApp.with(mContext).load(R.drawable.pw_invisible).into(mImgPwVisble);
//                    mImgPwVisble.setBackgroundResource(R.drawable.pw_invisible);
                }
                if (isShowPwd == 1) {
                    // 显示密码
                    mEtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    mEtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });

    }

    @Override
    protected UserRegistPresenter createPresenter() {
        return new UserRegistPresenter();
    }

    /**
     * 30秒才能发送一次
     */
    private void count() {
        final int time = 60;
        Flowable.interval(0, 1, TimeUnit.SECONDS)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .take(time + 1)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return time - aLong;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Subscription>() {
                    @Override
                    public void accept(Subscription subscription) throws Exception {
                        mTvVerify.setEnabled(false);
                    }
                })
                .subscribe(num -> {
                            mTvVerify.setText("剩余" + num + "秒");

                            if (num == 0) {
                                mTvVerify.setEnabled(true);
                                mTvVerify.setText("发送验证码");
                            }
                        }, throwable -> {

                        }
                        , () -> {
                            mTvVerify.setEnabled(true);
                            mTvVerify.setText("发送验证码");
                        }
                );
    }

    /**
     * 获取验证码成功&失败
     */
    @Override
    public void getVerifyCodeSuccess() {

    }

    @Override
    public void getVerifyCodeFail() {

    }

    /**
     * 注册成功&失败
     */
    @Override
    public void registSuccess(RegistRes response) {
        SPUtils.setString(TOKEN, response.getAccesstoken());
        SPUtils.setString(USERID, response.getAccesstoken());
        SPUtils.setString(USERNAME, response.getAccesstoken());
        startActivity(new Intent(mContext, HomeActivity.class));
    }

    @Override
    public void registFail() {

    }


    // 通过继承UnderlineSpan重写updateDrawState方法setUnderlineText(false)取消下划线
    class MyUnderlineSpan extends UnderlineSpan {

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setUnderlineText(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
